﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AppLab.Models;
using AppLab.Web;
using AppLab.Web.Services;
using Wicresoft.AppFlow.Flows;

namespace AppLab.Views
{
    public partial class Publish : Page
    {
        private IList<OperationBase> possiblyPendingOperations = new List<OperationBase>();
        private FlowContext flow = new FlowContext();
        private PublishSubmitData push = new PublishSubmitData();

        /// <summary>
        /// 控制每页DateGrid的行数
        /// </summary>
        private const int pageSize = 12;

        public Publish()
        {
            InitializeComponent();
            PageScrollViewer.SetIsMouseWheelScrollingEnabled(true);
            this.Title = ApplicationStrings.PublishPageTitle;
            this.DataContext = push;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            BindGrid(0,"");
            this.BindAutoCompleteOfMobileType();
        }

        #region 分页处理，每次加载一页

        private void BindGrid(int pageIndex,string type)
        {
            busyIndicatorLoad.IsBusy = true;

            InvokeOperation<int> iCount = flow.GetPublicCount(type);
            iCount.Completed += new EventHandler(iCount_Completed);

            var query = flow.GetPublicDataGridQuery(pageSize, pageIndex,type);
            LoadOperation<PublishSubmitData> loadOp = flow.Load(query, lp => busyIndicatorLoad.IsBusy = false, null);
            loadOp.Completed += new EventHandler(loadOp_Completed);
        }

        void loadOp_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOp = (LoadOperation)sender;
            dataGridPublish.ItemsSource = loadOp.Entities;
            dataGridPublish.SelectedIndex = 0;

            if (loadOp.TotalEntityCount <= 0)
            {
                //该页记录审核完，跳到第一页
                if (dpPulishInfo.PageIndex > 0)
                {
                    dpPulishInfo.PageIndex = 0;
                    BindGrid(0,this.autoCompleteBoxMbBrand.Text.Trim());
                }
                else
                {
                    this.detailInfo.IsHitTestVisible = false;
                    this.TipsForAdaptation.Text = ApplicationStrings.TipsForNoNewPublishedAdaptation;
                    this.TipsForAdaptation2.Text = string.Empty;
                }
            }
            else
            {
                this.detailInfo.IsHitTestVisible = true;
            }

            busyIndicatorLoad.IsBusy = false;
        }

        void iCount_Completed(object sender, EventArgs e)
        {
            InvokeOperation invokeOp = (InvokeOperation)sender;
            if (dpPulishInfo.PageIndex <= 0)
            {
                dpPulishInfo.BindSource((int)(invokeOp.Value), pageSize);
                dpPulishInfo.PageIndexChanged -= new EventHandler<EventArgs>(dpReviewInfo_PageIndexChanged);
                dpPulishInfo.PageIndexChanged += new EventHandler<EventArgs>(dpReviewInfo_PageIndexChanged);
            }
        }

        void dpReviewInfo_PageIndexChanged(object sender, EventArgs e)
        {
            BindGrid(dpPulishInfo.PageIndex, this.autoCompleteBoxMbBrand.Text.Trim());
        }

        #endregion

        private void buttonRelease_Click(object sender, RoutedEventArgs e)
        {
            if (!Verification()) return;

            PublishSubmitData psd = new PublishSubmitData();
            psd.FlowGuid = (dataGridPublish.SelectedItem as PublishSubmitData).FlowGuid;
            psd.MobileID = (dataGridPublish.SelectedItem as PublishSubmitData).MobileID;  //手机编号 
            psd.WebState = (bool)webCheck.IsChecked ? 1 : 0; //手机的发布状态(共5种)
            psd.WapState = (bool)wapCheck.IsChecked ? 2 : 0;
            psd.PreloadedState = (bool)preloadedCheck.IsChecked ? 3 : 0;
            psd.TysxSpaceState = (bool)tysxSpaceCheck.IsChecked ? 4 : 0;
            psd.TysxBoLuState = (bool)tysxBoLuCheck.IsChecked ? 5 : 0;

            push.CurrentOperation = this.flow.Publish(psd.FlowGuid, psd, this.PushOperation_Completed, null);
            this.possiblyPendingOperations.Add(push.CurrentOperation);
        }

        private void PushOperation_Completed(InvokeOperation<Guid> operation)
        {
            if (!operation.IsCanceled)
            {
                if (operation.HasError)
                {
                    ErrorWindow.CreateNew(operation.Error);
                    operation.MarkErrorAsHandled();
                }
                else if (operation.Value != Guid.Empty)
                {
                    MessageBox.Show(PopupDialogStrings.SuccessfulRelease, this.Title, MessageBoxButton.OK);
                    BindGrid(dpPulishInfo.PageIndex, this.autoCompleteBoxMbBrand.Text.Trim());
                    Clear();
                }
                else
                    ErrorWindow.CreateNew(ErrorResources.ErrorWindowGenericError);
            }
        }

        private bool Verification()
        {
            PublishSubmitData emp = dataGridPublish.SelectedItem as PublishSubmitData;

            #region Login

            if (!WebContext.Current.User.IsAuthenticated)
            {
                this.TipsForAdaptation.Text = string.Empty;
                this.TipsForAdaptation2.Text = PopupDialogStrings.MustBeLoggedInString;
                return false;
            }

            #endregion

            #region SelectedItem

            if (emp == null)
            {
                this.TipsForAdaptation.Text = string.Empty;
                this.TipsForAdaptation2.Text = PopupDialogStrings.SelectedReleasedClientOnPublish;
                return false;
            }

            #endregion

            #region SelectedState

            if (!((bool)webCheck.IsChecked || (bool)wapCheck.IsChecked || (bool)preloadedCheck.IsChecked || (bool)tysxSpaceCheck.IsChecked || (bool)tysxBoLuCheck.IsChecked))
            {
                this.TipsForAdaptation.Text = string.Empty;
                this.TipsForAdaptation2.Text = "请为 “" + emp.MobileBrand + "(" + emp.MobileType + ")" + "/" + emp.MobileVersion + "” " + ApplicationStrings.SelectedPublishWay;
                return false;
            }

            #endregion

            return true;
        }

        private void Clear()
        {
            webCheck.IsChecked = false;
            wapCheck.IsChecked = false;
            preloadedCheck.IsChecked = false;
            tysxSpaceCheck.IsChecked = false;
            tysxBoLuCheck.IsChecked = false;
        }

        private void dataGridPublish_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            PublishSubmitData psd = dataGridPublish.SelectedItem as PublishSubmitData;
            if (psd != null)
            {
                webCheck.IsChecked = psd.WebState != 1 ? false : true;
                wapCheck.IsChecked = psd.WapState != 2 ? false : true;
                preloadedCheck.IsChecked = psd.PreloadedState != 3 ? false : true;
                tysxSpaceCheck.IsChecked = psd.TysxSpaceState != 4 ? false : true;
                tysxBoLuCheck.IsChecked = psd.TysxBoLuState != 5 ? false : true;
                this.TipsForAdaptation2.Text = string.Empty;
                this.TipsForAdaptation.Text = psd.MobileBrand + "(" + psd.MobileType + ")" + ApplicationStrings.TipsForAdaptationPublishedStr;
            }
        }

        #region 搜索

        private ComboBox comb = new ComboBox();
        private void BindAutoCompleteOfMobileType()
        {
            var query = flow.GetMobileTypesQuery(-1);

            LoadOperation<MobileType> load = flow.Load(query);
            load.Completed += new EventHandler(load_Completed);
        }

        void load_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOp = (LoadOperation)sender;
            comb.ItemsSource = loadOp.Entities;
            BindAutoCompleteBox(comb);
        }

        private void BindAutoCompleteBox(ComboBox comb)
        {
            List<String> listStr = new List<string>();
            for (int i = 0; i < comb.Items.Count; i++)
            {
                MobileType e = comb.Items[i] as MobileType;
                listStr.Add(e.TypeName);
            }
            autoCompleteBoxMbBrand.ItemsSource = listStr;
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            this.dpPulishInfo.PageIndex = 0;
            BindGrid(this.dpPulishInfo.PageIndex, autoCompleteBoxMbBrand.Text.Trim());
        }
        #endregion
    }
}
